'use strict';
const { _pwd } = require('../../utils/cryp');
module.exports = (app) => {
  class UserService extends app.Service {
    // 注册
    async register() {
      const { app, ctx } = this;
      const { User } = app.model.Tables.Blog;
      const data = ctx.request.body;
      console.log('data', data);
      // 创建用户
      const registerRes = await User.create({
        phone: data.phone,
        name: data.name,
        password: data.password,
        projectId: data.projectId,
      });
      /** 删除密码信息 */
      registerRes.password = undefined;
      // registerRes.projectId = undefined;
      return registerRes;
    }
    // 登录
    async login() {
      const { app, ctx } = this;
      const { User } = app.model.Tables.Blog;
      const data = ctx.request.body;
      // 通过手机号查找
      const res = await User.findOne({
        where: {
          phone: data.phone,
        },
        // attributes: { exclude: ['password'] },
        raw: true,
      });

      // 检测账号是否存在
      if (res == null) {
        return '账号不存在';
      }
      // 检测密码
      // console.log(data.password, res.password);
      const Check = await ctx.compare(data.password, res.password);
      if (!Check) {
        return '用户密码错误';
      }
      // token过期时间 (默认一天)
      const expiresTime = new Date().getTime() + 24 * 60 * 60 * 1000;
      // 结合jwt生成携带信息的token
      const token = app.jwt.sign(
        {
          user_id: res.id,
          // 返回毫秒
          token_out_of_date: expiresTime,
          // ? 区分c端项目
          project_type: 'blog',
        },
        app.config.jwt.secret,
        {
          // 返回过期时间单位为秒
          expiresIn: '1 days',
        }
      );
      // exp - JWT的过期时间
      // iat - JWT的签发时间

      // 添加token到商家表，默认过期时间一天
      await User.update(
        {
          token,
          token_out_of_date: expiresTime,
          last_ip: ctx.request.ip,
        },
        {
          where: {
            id: res.id,
          },
        }
      );
      // 去除密码
      delete res.password;
      res.token = token;
      return res;
    }

    // 查找用户信息
    async searchUser() {
      const { app, ctx } = this;
      const { User } = app.model.Tables.Blog;
      const data = ctx.query;

      const res = await User.findOne({
        where: { id: Number(data.id) },
        attributes: [
          'id',
          'name',
          'avatar',
          'desc',
          'blogCount',
          'followCount',
          'fanCount',
          'commentCount',
          'replyCount',
        ],
      });
      return res;
    }
    // 关注
    async follow() {
      const { app, ctx } = this;
      const { User, Follow } = app.model.Tables.Blog;
      const data = ctx.request.body;

      const isUser = await User.findOne({
        where: {
          id: data.id,
          projectId: data.projectId,
        },
      });
      if (isUser) {
        const findRes = await Follow.findOne({
          where: {
            followUserId: ctx.userInfo.id,
            beFollowUserId: data.id,
          },
        });
        // 如果未关注
        if (findRes == null) {
          await Follow.create({
            followUserId: Number(ctx.userInfo.id),
            beFollowUserId: Number(data.id),
            projectId: data.projectId,
          });

          // 用户关注数自增1
          await User.findByPk(ctx.userInfo.id).then(function (user) {
            user.increment('followCount').then(function (user) {
              console.log('success');
            });
          });
          // 被关注用户粉丝数自增1
          await User.findByPk(data.id).then(function (user) {
            user.increment('fanCount').then(function (user) {
              console.log('success');
            });
          });
          return '关注成功';
        } // 已关注

        await Follow.destroy({
          where: {
            followUserId: ctx.userInfo.id,
            beFollowUserId: data.id,
            projectId: data.projectId,
          },
        });
        // 用户关注数自减1
        await User.findByPk(ctx.userInfo.id).then(function (user) {
          user.decrement('followCount').then(function (user) {
            console.log('success');
          });
        });
        // 被关注用户粉丝数自减1
        await User.findByPk(data.id).then(function (user) {
          user.decrement('fanCount').then(function (user) {
            console.log('success');
          });
        });
        return '取消关注成功';
      }
      return '用户不存在';
    }
    // 重置密码
    async resetPassword() {
      const { app, ctx } = this;
      const { User } = app.model.Tables.Blog;
      const data = ctx.request.body;

      // 对比密码是否一致
      const Check = await ctx.compare(
        String(data.oldPassword),
        ctx.userInfo.password
      );
      if (!Check) {
        return '密码验证失败';
      }
      /** 加密新密码 */
      const newPassword = await ctx.genHash(String(data.newPassword));

      const resetRes = await User.update(
        {
          password: newPassword,
        },
        {
          where: {
            id: ctx.userInfo.id,
          },
        }
      );
      return resetRes;
    }
    // 编辑个人信息
    async edit() {
      const { app, ctx } = this;
      const { User } = app.model.Tables.Blog;
      const data = ctx.request.body;
      // 获取token
      const token = ctx.get('x-token');
      const decode = app.jwt.decode(token);

      const res = await User.update(
        {
          name: data.name,
          avatar: data.avatar,
          desc: data.desc,
        },
        {
          where: {
            id: ctx.userInfo.id,
            projectId: data.projectId,
          },
        }
      );
      return res;
    }
    // 判断手机号是否已注册
    async isRegister() {
      const { app, ctx } = this;
      const { User } = app.model.Tables.Blog;
      const data = ctx.request.body;
      const res = await User.findOne({
        where: {
          phone: data.phone,
        },
      });
      if (res) {
        return '手机号已注册';
      }
      return '手机号未注册';
    }
    // 获取点赞的博客
    async getLikeBlog() {
      const { app, ctx } = this;
      const { LikeBlog, Blog, BlogClassify } = app.model.Tables.Blog;
      const data = ctx.request.query;

      // 查找点赞记录
      const res = await LikeBlog.findAndCountAll({
        where: {
          likeUserId: ctx.userInfo.id,
        },
        limit: Number(data.limit) || 10,
        offset: Number(data.offset) || 0,
      });
      // console.log(res);
      // console.log(res.rows[0].dataValues);
      // 根据点赞记录查找博客信息
      for (let i = 0; i < res.rows.length; i++) {
        const bRes = await Blog.findByPk(res.rows[i].dataValues.blogId, {
          include: [
            {
              model: BlogClassify,
              // 字段
              attributes: ['classifyId', 'classifyName'],
            },
          ],
        });
        if (!bRes) {
          res.rows[i].dataValues.blog = '该文章已删除';
        } else {
          res.rows[i].dataValues.blog = bRes.dataValues;
        }
      }
      return res;
    }

    async getLikeUser() {
      const { app, ctx } = this;
      const { User, Follow } = app.model.Tables.Blog;
      const data = ctx.request.body;
      const res = await Follow.findAndCountAll({
        where: {
          followUserId: ctx.userInfo.id,
        },
        limit: Number(data.limit) || 10,
        offset: Number(data.offset) || 0,
      });
      // 根据关注记录查找被关注的用户信息
      for (let i = 0; i < res.rows.length; i++) {
        const uRes = await User.findByPk(res.rows[i].beFollowUserId, {
          attributes: ['phone', 'name', 'avatar', 'desc'],
        });
        res.rows[i].dataValues.user = uRes.dataValues;
      }
      return res;
    }
  }
  return UserService;
};
